<!DOCTYPE html>
<html lang=zh>
<head>
  <meta charset="utf-8">
  
  <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, minimum-scale=1, user-scalable=no, minimal-ui">
  <meta name="renderer" content="webkit">
  <meta http-equiv="Cache-Control" content="no-transform" />
  <meta http-equiv="Cache-Control" content="no-siteapp" />
  <meta name="apple-mobile-web-app-capable" content="yes">
  <meta name="apple-mobile-web-app-status-bar-style" content="black">
  <meta name="format-detection" content="telephone=no,email=no,adress=no">
  <!-- Color theme for statusbar -->
  <meta name="theme-color" content="#000000" />
  <!-- 强制页面在当前窗口以独立页面显示,防止别人在框架里调用页面 -->
  <meta http-equiv="window-target" content="_top" />
  
  
  <title>一文带你了解JWT以及在Nodejs中的应用 | DiDi</title>
  <meta name="description" content="JWTJson Web Token (简称JWT). 是一种开放标准(RFC 7519), 是目前较为流行的跨域认证解决方案，常被用于身份验证和授权机制。 常见的Session 用户认证方案在谈论JWT之前，我们先聊聊session。目前我们最常见的用户认证方案是在当前会话（session）里面保存相关数据，客户端请求的的时候带上session以用来验证用户登录情况。大概步骤如下：  登录窗口，用">
<meta property="og:type" content="article">
<meta property="og:title" content="一文带你了解JWT以及在Nodejs中的应用">
<meta property="og:url" content="https://guoyayunhappy.gitee.io/didiblog/2023/12/16/jwt-demonstration/index.html">
<meta property="og:site_name" content="Hexo">
<meta property="og:description" content="JWTJson Web Token (简称JWT). 是一种开放标准(RFC 7519), 是目前较为流行的跨域认证解决方案，常被用于身份验证和授权机制。 常见的Session 用户认证方案在谈论JWT之前，我们先聊聊session。目前我们最常见的用户认证方案是在当前会话（session）里面保存相关数据，客户端请求的的时候带上session以用来验证用户登录情况。大概步骤如下：  登录窗口，用">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://guoyayunhappy.gitee.io/didiblog/images/jwt-demonstration/jwt-demo-picture1.png">
<meta property="og:image" content="https://guoyayunhappy.gitee.io/didiblog/images/jwt-demonstration/jwt-demo-picture2.png">
<meta property="og:image" content="https://guoyayunhappy.gitee.io/didiblog/images/jwt-demonstration/jwt-demo-picture3.png">
<meta property="og:image" content="https://guoyayunhappy.gitee.io/didiblog/images/jwt-demonstration/jwt-demo-picture4.png">
<meta property="og:image" content="https://guoyayunhappy.gitee.io/didiblog/images/jwt-demonstration/jwt-demo-picture5.png">
<meta property="og:image" content="https://guoyayunhappy.gitee.io/didiblog/images/jwt-demonstration/jwt-demo-picture6.png">
<meta property="article:published_time" content="2023-12-16T03:37:46.000Z">
<meta property="article:modified_time" content="2023-12-16T07:27:14.427Z">
<meta property="article:author" content="John Doe">
<meta property="article:tag" content="JS">
<meta property="article:tag" content="Nodejs">
<meta property="article:tag" content="Token">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://guoyayunhappy.gitee.io/didiblog/images/jwt-demonstration/jwt-demo-picture1.png">
  <!-- Canonical links -->
  <link rel="canonical" href="https://guoyayunhappy.gitee.io/didiblog/2023/12/16/jwt-demonstration/index.html">
  
    <link rel="alternate" href="/atom.xml" title="Hexo" type="application/atom+xml">
  
  
    <link rel="icon" href="images/favatar/idesign-logo.png" type="image/x-icon">
  
  
<link rel="stylesheet" href="/didiblog/css/style.css">

  
  
  
  
<meta name="generator" content="Hexo 7.3.0"></head>


<body class="main-center theme-black" itemscope itemtype="http://schema.org/WebPage">
  <header class="header" itemscope itemtype="http://schema.org/WPHeader">
  <div class="slimContent">
    <div class="navbar-header">
      
      
      <div class="profile-block text-center">
        <a id="avatar" href="https://gitee.com/GuoyayunHappy" target="_blank">
          <img class="img-circle img-rotate" src="/didiblog/images/avatar.jpg" width="200" height="200">
        </a>
        <h2 id="name" class="hidden-xs hidden-sm">一枚@大帅锅</h2>
        <h3 id="title" class="hidden-xs hidden-sm hidden-md">CV工程师</h3>
        <small id="location" class="text-muted hidden-xs hidden-sm"><i class="icon icon-map-marker"></i> Shanghai, China</small>
      </div>
      
      <div class="search" id="search-form-wrap">

    <form class="search-form sidebar-form">
        <div class="input-group">
            <input type="text" class="search-form-input form-control" placeholder="搜索" />
            <span class="input-group-btn">
                <button type="submit" class="search-form-submit btn btn-flat" onclick="return false;"><i class="icon icon-search"></i></button>
            </span>
        </div>
    </form>
    <div class="ins-search">
  <div class="ins-search-mask"></div>
  <div class="ins-search-container">
    <div class="ins-input-wrapper">
      <input type="text" class="ins-search-input" placeholder="想要查找什么..." x-webkit-speech />
      <button type="button" class="close ins-close ins-selectable" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
    </div>
    <div class="ins-section-wrapper">
      <div class="ins-section-container"></div>
    </div>
  </div>
</div>


</div>
      <button class="navbar-toggle collapsed" type="button" data-toggle="collapse" data-target="#main-navbar" aria-controls="main-navbar" aria-expanded="false">
        <span class="sr-only">Toggle navigation</span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
      </button>
    </div>
    <nav id="main-navbar" class="collapse navbar-collapse" itemscope itemtype="http://schema.org/SiteNavigationElement" role="navigation">
      <ul class="nav navbar-nav main-nav menu-highlight">
        
        
        <li class="menu-item menu-item-home">
          <a href="/didiblog/.">
            
            <i class="icon icon-home-fill"></i>
            
            <span class="menu-title">首页</span>
          </a>
        </li>
        
        
        <li class="menu-item menu-item-archives">
          <a href="/didiblog/archives">
            
            <i class="icon icon-archives-fill"></i>
            
            <span class="menu-title">归档</span>
          </a>
        </li>
        
        
        <li class="menu-item menu-item-categories">
          <a href="/didiblog/categories">
            
            <i class="icon icon-folder"></i>
            
            <span class="menu-title">分类</span>
          </a>
        </li>
        
        
        <li class="menu-item menu-item-tags">
          <a href="/didiblog/tags">
            
            <i class="icon icon-tags"></i>
            
            <span class="menu-title">标签</span>
          </a>
        </li>
        
        
        <li class="menu-item menu-item-links">
          <a href="/didiblog/links">
            
            <i class="icon icon-friendship"></i>
            
            <span class="menu-title">友链</span>
          </a>
        </li>
        
        
        <li class="menu-item menu-item-about">
          <a href="/didiblog/about">
            
            <i class="icon icon-cup-fill"></i>
            
            <span class="menu-title">关于</span>
          </a>
        </li>
        
      </ul>
      
	
    <ul class="social-links">
    	
        <li><a href="https://gitee.com/GuoyayunHappy" target="_blank" title="Github" data-toggle=tooltip data-placement=top><i class="icon icon-github"></i></a></li>
        
        <li><a href="/didiblog/atom.xml" target="_blank" title="Rss" data-toggle=tooltip data-placement=top><i class="icon icon-rss"></i></a></li>
        
    </ul>

    </nav>
  </div>
</header>

  
    <aside class="sidebar" itemscope itemtype="http://schema.org/WPSideBar">
  <div class="slimContent">
    
      <div class="widget">
    <h3 class="widget-title">公告</h3>
    <div class="widget-body">
        <div id="board">
            <div class="content">
                <p>让coding更有趣!</p>
            </div>
        </div>
    </div>
</div>

    
      
  <div class="widget">
    <h3 class="widget-title">分类</h3>
    <div class="widget-body">
      <ul class="category-list"><li class="category-list-item"><a class="category-list-link" href="/didiblog/categories/JS/">JS</a><span class="category-list-count">6</span></li><li class="category-list-item"><a class="category-list-link" href="/didiblog/categories/TS/">TS</a><span class="category-list-count">1</span></li><li class="category-list-item"><a class="category-list-link" href="/didiblog/categories/%E7%BD%91%E7%AB%99/">网站</a><span class="category-list-count">1</span><ul class="category-list-child"><li class="category-list-item"><a class="category-list-link" href="/didiblog/categories/%E7%BD%91%E7%AB%99/html/">html</a><span class="category-list-count">1</span></li></ul></li></ul>
    </div>
  </div>


    
      
  <div class="widget">
    <h3 class="widget-title">标签</h3>
    <div class="widget-body">
      <ul class="tag-list" itemprop="keywords"><li class="tag-list-item"><a class="tag-list-link" href="/didiblog/tags/HTML/" rel="tag">HTML</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="/didiblog/tags/HTTP/" rel="tag">HTTP</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="/didiblog/tags/HTTPS/" rel="tag">HTTPS</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="/didiblog/tags/JS/" rel="tag">JS</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="/didiblog/tags/Nodejs/" rel="tag">Nodejs</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="/didiblog/tags/Token/" rel="tag">Token</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="/didiblog/tags/cookie/" rel="tag">cookie</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="/didiblog/tags/js/" rel="tag">js</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="/didiblog/tags/typescript/" rel="tag">typescript</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="/didiblog/tags/%E6%80%A7%E8%83%BD%E4%BC%98%E5%8C%96/" rel="tag">性能优化</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="/didiblog/tags/%E7%AE%97%E6%B3%95/" rel="tag">算法</a><span class="tag-list-count">2</span></li><li class="tag-list-item"><a class="tag-list-link" href="/didiblog/tags/%E7%BC%93%E5%AD%98/" rel="tag">缓存</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="/didiblog/tags/%E8%AE%BE%E8%AE%A1%E6%A8%A1%E5%BC%8F/" rel="tag">设计模式</a><span class="tag-list-count">3</span></li><li class="tag-list-item"><a class="tag-list-link" href="/didiblog/tags/%E8%B7%A8%E5%9F%9F/" rel="tag">跨域</a><span class="tag-list-count">1</span></li></ul>
    </div>
  </div>


    
      
  <div class="widget">
    <h3 class="widget-title">标签云</h3>
    <div class="widget-body tagcloud">
      <a href="/didiblog/tags/HTML/" style="font-size: 13px;">HTML</a> <a href="/didiblog/tags/HTTP/" style="font-size: 13px;">HTTP</a> <a href="/didiblog/tags/HTTPS/" style="font-size: 13px;">HTTPS</a> <a href="/didiblog/tags/JS/" style="font-size: 13px;">JS</a> <a href="/didiblog/tags/Nodejs/" style="font-size: 13px;">Nodejs</a> <a href="/didiblog/tags/Token/" style="font-size: 13px;">Token</a> <a href="/didiblog/tags/cookie/" style="font-size: 13px;">cookie</a> <a href="/didiblog/tags/js/" style="font-size: 13px;">js</a> <a href="/didiblog/tags/typescript/" style="font-size: 13px;">typescript</a> <a href="/didiblog/tags/%E6%80%A7%E8%83%BD%E4%BC%98%E5%8C%96/" style="font-size: 13px;">性能优化</a> <a href="/didiblog/tags/%E7%AE%97%E6%B3%95/" style="font-size: 13.5px;">算法</a> <a href="/didiblog/tags/%E7%BC%93%E5%AD%98/" style="font-size: 13px;">缓存</a> <a href="/didiblog/tags/%E8%AE%BE%E8%AE%A1%E6%A8%A1%E5%BC%8F/" style="font-size: 14px;">设计模式</a> <a href="/didiblog/tags/%E8%B7%A8%E5%9F%9F/" style="font-size: 13px;">跨域</a>
    </div>
  </div>

    
      
  <div class="widget">
    <h3 class="widget-title">归档</h3>
    <div class="widget-body">
      <ul class="archive-list"><li class="archive-list-item"><a class="archive-list-link" href="/didiblog/archives/2025/07/">七月 2025</a><span class="archive-list-count">2</span></li><li class="archive-list-item"><a class="archive-list-link" href="/didiblog/archives/2025/06/">六月 2025</a><span class="archive-list-count">1</span></li><li class="archive-list-item"><a class="archive-list-link" href="/didiblog/archives/2024/03/">三月 2024</a><span class="archive-list-count">1</span></li><li class="archive-list-item"><a class="archive-list-link" href="/didiblog/archives/2024/02/">二月 2024</a><span class="archive-list-count">1</span></li><li class="archive-list-item"><a class="archive-list-link" href="/didiblog/archives/2023/12/">十二月 2023</a><span class="archive-list-count">1</span></li><li class="archive-list-item"><a class="archive-list-link" href="/didiblog/archives/2023/10/">十月 2023</a><span class="archive-list-count">1</span></li><li class="archive-list-item"><a class="archive-list-link" href="/didiblog/archives/2023/02/">二月 2023</a><span class="archive-list-count">7</span></li></ul>
    </div>
  </div>


    
      
  <div class="widget">
    <h3 class="widget-title">最新文章</h3>
    <div class="widget-body">
      <ul class="recent-post-list list-unstyled no-thumbnail">
        
          <li>
            
            <div class="item-inner">
              <p class="item-category">
                
              </p>
              <p class="item-title">
                <a href="/didiblog/2025/07/28/browser-cache/" class="title">用代码实践浏览器的强缓存和协商缓存</a>
              </p>
              <p class="item-date">
                <time datetime="2025-07-28T06:54:53.000Z" itemprop="datePublished">2025-07-28</time>
              </p>
            </div>
          </li>
          
          <li>
            
            <div class="item-inner">
              <p class="item-category">
                <a class="category-link" href="/didiblog/categories/JS/">JS</a>
              </p>
              <p class="item-title">
                <a href="/didiblog/2025/07/18/tail-call-optimization/" class="title">尾调用优化</a>
              </p>
              <p class="item-date">
                <time datetime="2025-07-18T11:53:08.000Z" itemprop="datePublished">2025-07-18</time>
              </p>
            </div>
          </li>
          
          <li>
            
            <div class="item-inner">
              <p class="item-category">
                
              </p>
              <p class="item-title">
                <a href="/didiblog/2025/06/17/interview/" class="title">interview</a>
              </p>
              <p class="item-date">
                <time datetime="2025-06-17T03:52:38.000Z" itemprop="datePublished">2025-06-17</time>
              </p>
            </div>
          </li>
          
          <li>
            
            <div class="item-inner">
              <p class="item-category">
                
              </p>
              <p class="item-title">
                <a href="/didiblog/2024/03/03/find-hamilton-path/" class="title">Javascript实现寻找哈密尔顿回路</a>
              </p>
              <p class="item-date">
                <time datetime="2024-03-03T00:18:45.000Z" itemprop="datePublished">2024-03-03</time>
              </p>
            </div>
          </li>
          
          <li>
            
            <div class="item-inner">
              <p class="item-category">
                
              </p>
              <p class="item-title">
                <a href="/didiblog/2024/02/21/better-to-know-signature-and-certificate/" class="title">一文读懂加密，摘要，数字签名和证书</a>
              </p>
              <p class="item-date">
                <time datetime="2024-02-21T03:22:45.000Z" itemprop="datePublished">2024-02-21</time>
              </p>
            </div>
          </li>
          
      </ul>
    </div>
  </div>
  

    
  </div>
</aside>

  
  
<main class="main" role="main">
  <div class="content">
  <article id="post-jwt-demonstration" class="article article-type-post" itemscope itemtype="http://schema.org/BlogPosting">
    
    <div class="article-header">
      
        
  
    <h1 class="article-title" itemprop="name">
      一文带你了解JWT以及在Nodejs中的应用
    </h1>
  

      
      <div class="article-meta">
        <span class="article-date">
    <i class="icon icon-calendar-check"></i>
	<a href="/didiblog/2023/12/16/jwt-demonstration/" class="article-date">
	  <time datetime="2023-12-16T03:37:46.000Z" itemprop="datePublished">2023-12-16</time>
	</a>
</span>
        
  <span class="article-category">
    <i class="icon icon-folder"></i>
    <a class="article-category-link" href="/didiblog/categories/JS/">JS</a>
  </span>

        
  <span class="article-tag">
    <i class="icon icon-tags"></i>
	<a class="article-tag-link-link" href="/didiblog/tags/JS/" rel="tag">JS</a>, <a class="article-tag-link-link" href="/didiblog/tags/Nodejs/" rel="tag">Nodejs</a>, <a class="article-tag-link-link" href="/didiblog/tags/Token/" rel="tag">Token</a>
  </span>


        

        <span class="post-comment"><i class="icon icon-comment"></i> <a href="/didiblog/2023/12/16/jwt-demonstration/#comments" class="article-comment-link">评论</a></span>
        
      </div>
    </div>
    <div class="article-entry marked-body" itemprop="articleBody">
      
        <h2 id="JWT"><a href="#JWT" class="headerlink" title="JWT"></a>JWT</h2><p>Json Web Token (简称JWT). 是一种开放标准(RFC 7519), 是目前较为流行的跨域认证解决方案，常被用于身份验证和授权机制。</p>
<h2 id="常见的Session-用户认证方案"><a href="#常见的Session-用户认证方案" class="headerlink" title="常见的Session 用户认证方案"></a>常见的Session 用户认证方案</h2><p>在谈论JWT之前，我们先聊聊session。目前我们最常见的用户认证方案是在当前会话（session）里面保存相关数据，客户端请求的的时候带上session以用来验证用户登录情况。大概步骤如下：</p>
<ol>
<li>登录窗口，用户输入账号和密码向服务器发送登录请求</li>
<li>服务器收到请求，验证通过后，在当前会话(session)里面保存相关数据，比如用户角色，登录时间等。</li>
<li>服务器会根据这个session生成一个sessionId，返回给客户端，并写入用户的cookie中。</li>
<li>随后用户的每一次请求，都会通过cookie,将seesionID传给服务器</li>
<li>服务器收到sessionID就会验证当前用户身份和状态<blockquote>
<p>这种方案肯定是没问题的，但也有一些缺点。第一就是扩展性不好，如果是服务器集群，就需要seession数据共享，保证每台服务器都能读取session</p>
</blockquote>
</li>
</ol>
<h2 id="JWT数据结构"><a href="#JWT数据结构" class="headerlink" title="JWT数据结构"></a>JWT数据结构</h2><p>JWT是一个长的字符串，中间用点(.)分割成3部分。大概长这样：</p>
<p><img src="/didiblog/images/jwt-demonstration/jwt-demo-picture1.png" alt="image.png"><br>它的三个部分依次如下：</p>
<h3 id="Header-头部"><a href="#Header-头部" class="headerlink" title="Header (头部)"></a>Header (头部)</h3><p>Header部分是一个JSON对象，描述JWT的元数据，如下：</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">&#123;</span><br><span class="line">&quot;algorithm&quot;: &quot;HS256&quot; ,</span><br><span class="line">&quot;type&quot;: &quot;JWT</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>上面代码中，表示签名算法用的是HS256(HMAC SHA256); <code>type</code> 表示这个令牌的类型。最后用Base64URL算法将上面的JSON对象转成字符串</p>
<h3 id="Payload-负载"><a href="#Payload-负载" class="headerlink" title="Payload (负载)"></a>Payload (负载)</h3><p>Payload部分也是一个JSON对象，用来存放实际要传递的数据。JWT规定了7个字段，分别是以下7个：</p>
<ol>
<li>iss(issuer):签发人</li>
<li>exp(expiration time):过期时间</li>
<li>sub(subject):主题</li>
<li>aud(audience):受众</li>
<li>nbf(Not before):生效时间</li>
<li>iat(Issued At):签发时间</li>
<li>jti(JWT ID):编号<blockquote>
<p>当然除了官方字段，你也可以定义私有字段(JWT默认是不加密的，所以不要把敏感信息放在这里)，如：</p>
</blockquote>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">&#123;</span><br><span class="line">&quot;sub&quot;: &quot;liebiao&quot;,</span><br><span class="line">&quot;admin&quot;: true</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
这个Payload对象也会被Base64URL算法转成字符串</li>
</ol>
<h3 id="Signature-签名"><a href="#Signature-签名" class="headerlink" title="Signature(签名)"></a>Signature(签名)</h3><p>Signature部分是对前两部分的签名，防止数据篡改。这里需要指定一个密钥(secret)，可以是个字符串，只有服务端才知道，然后使用Header里面指定的签名算法，按照以下公式产生签名，最终生成JWT字符串。</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">HMACSHA256(</span><br><span class="line">  base64UrlEncode(header) + &quot;.&quot; +</span><br><span class="line">  base64UrlEncode(payload),</span><br><span class="line">  secret)</span><br></pre></td></tr></table></figure>
<h2 id="JWT的使用"><a href="#JWT的使用" class="headerlink" title="JWT的使用"></a>JWT的使用</h2><p>客户端当收到服务端返回的JWT时，可以存在Cookie里或者localStorage.<br>随后，客户端与服务端的通信都要带上这个JWT，可以放在Cookie里自动发送但是不能跨域，更好的做法是放在HTTP的请求头<code>Authorization</code>字段里面</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">fetch(url,&#123;</span><br><span class="line">    method: &#x27;POST&#x27;,</span><br><span class="line">    headers: &#123;</span><br><span class="line">        &#x27;authorization&#x27;: token,</span><br><span class="line">    &#125;</span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure>
<h2 id="使用案例"><a href="#使用案例" class="headerlink" title="使用案例"></a>使用案例</h2><p>下面就用Node.js在本地实现下JWT的基本用法。</p>
<h3 id="需求背景"><a href="#需求背景" class="headerlink" title="需求背景"></a>需求背景</h3><p>用户访问网站主页不需要登录，但是当访问产品列表的时候需要登录，这时候我们可以让用户输入账号和密码，服务端验证通过后返回一个JWT给客户端，客户端讲JWT存到localstorage，随后再去访问产品列表的时候就在请求头的<code>Authorization</code>字段带上JWT，服务端验证成功返回产品列表，就不用再重复登录了。</p>
<h3 id="前端页面"><a href="#前端页面" class="headerlink" title="前端页面"></a>前端页面</h3><p>这里懒得搭建react环境，所以我直接引入的react，react-dom包和babel编译包。用的是react16,版本有点老了，但是不影响阅读。</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line">**index.html**</span><br><span class="line">&lt;!DOCTYPE html&gt;</span><br><span class="line">&lt;html lang=&quot;en&quot;&gt;</span><br><span class="line">&lt;head&gt;</span><br><span class="line">    &lt;meta charset=&quot;UTF-8&quot;&gt;</span><br><span class="line">    &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1.0&quot;&gt;</span><br><span class="line">    &lt;meta http-equiv=&quot;X-UA-Compatible&quot; content=&quot;ie=edge&quot;&gt;</span><br><span class="line">    &lt;title&gt;Document&lt;/title&gt;</span><br><span class="line">&lt;/head&gt;</span><br><span class="line">&lt;body&gt;</span><br><span class="line">    &lt;div id=&quot;container&quot;&gt;&lt;/div&gt;</span><br><span class="line">    &lt;script crossorigin src=&quot;https://unpkg.com/react@16/umd/react.development.js&quot;&gt;&lt;/script&gt;</span><br><span class="line">    &lt;script crossorigin src=&quot;https://unpkg.com/react-dom@16/umd/react-dom.development.js&quot;&gt;&lt;/script&gt;</span><br><span class="line">    &lt;script src=&quot;https://unpkg.com/babel-standalone@6.15.0/babel.min.js&quot;&gt;&lt;/script&gt;</span><br><span class="line">    &lt;script type=&quot;text/babel&quot; src=&quot;./index.js&quot;&gt;&lt;/script&gt;</span><br><span class="line">&lt;/body&gt;</span><br><span class="line">&lt;/html&gt;</span><br></pre></td></tr></table></figure>
<p>index.js 文件</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br></pre></td><td class="code"><pre><span class="line">index.js</span><br><span class="line">class App extends React.Component &#123;</span><br><span class="line">    constructor(props) &#123;</span><br><span class="line">        super(props);</span><br><span class="line">        this.state = &#123;</span><br><span class="line">            isShowButton: true,</span><br><span class="line">            isShowLogin: false,</span><br><span class="line">            userName: &#x27;&#x27;,</span><br><span class="line">            password: &#x27;&#x27;,</span><br><span class="line">            dataList: [],</span><br><span class="line">        &#125;;</span><br><span class="line">        this.renderData = this.renderData.bind(this);</span><br><span class="line">        this.renderLogin = this.renderLogin.bind(this);</span><br><span class="line">        this.getProductList = this.getProductList.bind(this);</span><br><span class="line">        this.goLogin = this.goLogin.bind(this);</span><br><span class="line"></span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    getProductList() &#123;</span><br><span class="line">        console.log(&#x27;local&#x27;, localStorage)</span><br><span class="line">        const token = localStorage.getItem(&#x27;token&#x27;);</span><br><span class="line">        fetch(&#x27;/user/getlist&#x27;, &#123;</span><br><span class="line">            method: &#x27;GET&#x27;,</span><br><span class="line">            headers: &#123;</span><br><span class="line">                &#x27;Content-Type&#x27;: &#x27;application/json&#x27;,</span><br><span class="line">                &#x27;authorization&#x27;: token</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;).then(res =&gt; &#123;</span><br><span class="line">            res.json().then((result) =&gt; &#123;</span><br><span class="line">                if (result.status === 200) &#123;</span><br><span class="line">                    this.setState(&#123;</span><br><span class="line">                        isShowButton: false,</span><br><span class="line">                        isShowLogin: false,</span><br><span class="line">                        dataList: result.data,</span><br><span class="line">                    &#125;)</span><br><span class="line">                    return;</span><br><span class="line">                &#125;</span><br><span class="line">                if (result.status === 403) &#123;</span><br><span class="line">                    console.log(result.msg);</span><br><span class="line">                    this.setState(&#123;</span><br><span class="line">                        isShowButton: false,</span><br><span class="line">                        isShowLogin: true</span><br><span class="line">                    &#125;)</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;)</span><br><span class="line">        &#125;)</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    goLogin() &#123;</span><br><span class="line">        const &#123; userName, password &#125; = this.state; </span><br><span class="line">        fetch(&#x27;/user/login&#x27;, &#123;</span><br><span class="line">            method: &#x27;POST&#x27;,</span><br><span class="line">            headers: &#123;</span><br><span class="line">                &#x27;Content-Type&#x27;: &#x27;application/json&#x27;,</span><br><span class="line">            &#125;,</span><br><span class="line">            body: JSON.stringify(&#123; userName, password&#125;)</span><br><span class="line">        &#125;).then((res) =&gt; &#123;</span><br><span class="line">            res.json().then((result) =&gt; &#123;</span><br><span class="line">                if (result.status === 200) &#123;</span><br><span class="line">                    console.log(&#x27;local&#x27;, localStorage)</span><br><span class="line">                    localStorage.setItem(&#x27;token&#x27;, result.token);</span><br><span class="line">                    this.setState(&#123;</span><br><span class="line">                        isShowButton: true,</span><br><span class="line">                        isShowLogin: false,</span><br><span class="line">                    &#125;);</span><br><span class="line">                    return;</span><br><span class="line">                &#125;</span><br><span class="line">                alert(`login err, status is: $&#123;result.status&#125;, reason is: $&#123;result.msg&#125;`);</span><br><span class="line">            &#125;)</span><br><span class="line">        &#125;).catch((e) =&gt; &#123;</span><br><span class="line">            alert(&#x27;login failed: &#x27;, e.message);</span><br><span class="line">        &#125;)</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    renderLogin() &#123;</span><br><span class="line">        const &#123; userName, password &#125; = this.state;</span><br><span class="line">        return &lt;div&gt;</span><br><span class="line">            &lt;div&gt;账号： &lt;input value=&#123;userName&#125; onChange=&#123;(e) =&gt; &#123; this.setState(&#123; userName: e.target.value &#125;)&#125;&#125; /&gt;&lt;/div&gt;    </span><br><span class="line">            &lt;div&gt;密码： &lt;input value=&#123;password&#125; onChange=&#123;(e) =&gt; &#123; this.setState(&#123; password: e.target.value &#125;)&#125;&#125; /&gt;&lt;/div&gt;    </span><br><span class="line">            &lt;div&gt;&lt;button onClick=&#123;this.goLogin&#125;&gt;登录&lt;/button&gt;&lt;/div&gt;    </span><br><span class="line">        &lt;/div&gt;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    renderData() &#123;</span><br><span class="line">        const &#123; dataList &#125; = this.state;</span><br><span class="line">        return dataList.map(item =&gt; &#123;</span><br><span class="line">            return &lt;div key=&#123;item.name&#125;&gt;Product is &#123;item.name&#125;, Price is &#123;item.price&#125;&lt;/div&gt;</span><br><span class="line">        &#125;);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    render() &#123;</span><br><span class="line">        return &lt;div&gt;</span><br><span class="line">            &#123; this.state.isShowButton &amp;&amp; &lt;button onClick=&#123;this.getProductList&#125;&gt;查看列表&lt;/button&gt; &#125;    </span><br><span class="line">            &#123; this.state.isShowLogin &amp;&amp; this.renderLogin() &#125;    </span><br><span class="line">            &#123; this.state.dataList.length ? this.renderData() : null&#125;    </span><br><span class="line">        &lt;/div&gt;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line">const container = document.querySelector(&#x27;#container&#x27;);</span><br><span class="line">ReactDOM.render(&lt;App/&gt;, container);</span><br><span class="line"></span><br></pre></td></tr></table></figure>
<h3 id="服务端"><a href="#服务端" class="headerlink" title="服务端"></a>服务端</h3><p>服务端用的是express框架，简单易上手。 这里引入了一个<code>require(&#39;./jwt&#39;)</code>的文件，这个我们稍后介绍。首先用app.use()拦截了所有请求，如果是请求的<code>user/getList</code>则需要验证用户登录状态，如果请求头没有token或者token不合法则返回403状态码给到客户端。客户端就会显示登录页要求用户登录，这里申明了一个<code>userList</code>的JSON数组用来模拟数据库存储的客户信息，当用户登录的信息匹配某条数据时则表示该用户是合法用户，随后返回JWT以及产品列表给客户端。</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br></pre></td><td class="code"><pre><span class="line">**server.js**</span><br><span class="line">const JwtUtil = require(&#x27;./jwt&#x27;);</span><br><span class="line">const express = require(&#x27;express&#x27;);</span><br><span class="line">const path = require(&quot;path&quot;);</span><br><span class="line">const app = express();</span><br><span class="line">const userList = [&#123;</span><br><span class="line">    userName: &#x27;guoguo&#x27;,</span><br><span class="line">    password: &#x27;123&#x27;,</span><br><span class="line">    _id: &#x27;2873492791&#x27;</span><br><span class="line">&#125;, &#123;</span><br><span class="line">    userName: &#x27;tt&#x27;,</span><br><span class="line">    password: &#x27;111&#x27;,</span><br><span class="line">    _id: &#x27;287sdkjfoii&#x27;</span><br><span class="line">&#125;];</span><br><span class="line">const dataList = [&#123;</span><br><span class="line">    product: &#x27;Apple&#x27;,</span><br><span class="line">    price: 12</span><br><span class="line">&#125;, &#123;</span><br><span class="line">    product: &#x27;Banana&#x27;,</span><br><span class="line">    price: 20</span><br><span class="line">&#125;];</span><br><span class="line"></span><br><span class="line">app.use(express.static(path.resolve(__dirname, &quot;../public&quot;)));</span><br><span class="line">app.use(express.json());</span><br><span class="line"></span><br><span class="line">app.use(function (req, res, next) &#123;</span><br><span class="line">    // 获取列表需要校验token</span><br><span class="line">    console.log(&#x27;result is: &#x27;, req.url);</span><br><span class="line">    if (req.url === &#x27;/user/getlist&#x27;) &#123;</span><br><span class="line">        const token = req.headers.authorization;</span><br><span class="line">        const jwt = new JwtUtil(token);</span><br><span class="line">        const result = jwt.verifyToken();</span><br><span class="line">        if (result.status) &#123;</span><br><span class="line">            next();</span><br><span class="line">        &#125; else &#123;</span><br><span class="line">            res.send(&#123;</span><br><span class="line">                status: 403,</span><br><span class="line">                msg: result.msg</span><br><span class="line">            &#125;);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125; else &#123;</span><br><span class="line">        // 不需要做token校验的请求直接进行下一步</span><br><span class="line">        next();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;)</span><br><span class="line"></span><br><span class="line">app.post(&#x27;/user/login&#x27;, function (req, res) &#123;</span><br><span class="line">    console.log(&#x27;req is: &#x27;, req.body);</span><br><span class="line">    const &#123;</span><br><span class="line">        userName,</span><br><span class="line">        password</span><br><span class="line">    &#125; = req.body;</span><br><span class="line">    new Promise((resolve, reject) =&gt; &#123;</span><br><span class="line">        const user = userList.find(item =&gt; item.userName === userName);</span><br><span class="line">        if (user &amp;&amp; user.password === password) &#123;</span><br><span class="line">            // 用户已存在于数据库中</span><br><span class="line">            resolve(user);</span><br><span class="line">        &#125; else &#123;</span><br><span class="line">            reject(&#x27;user is not exist&#x27;);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;).then(result =&gt; &#123;</span><br><span class="line">        if (result) &#123;</span><br><span class="line">            const jwt = new JwtUtil(result._id);</span><br><span class="line">            const token = jwt.generateToken();</span><br><span class="line">            if (token) &#123;</span><br><span class="line">                res.send(&#123;</span><br><span class="line">                    status: 200,</span><br><span class="line">                    msg: &#x27;login success&#x27;,</span><br><span class="line">                    token</span><br><span class="line">                &#125;);</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;).catch((e) =&gt; &#123;</span><br><span class="line">        res.send(&#123;</span><br><span class="line">            status: 404,</span><br><span class="line">            msg: e</span><br><span class="line">        &#125;);</span><br><span class="line">    &#125;)</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">&#125;)</span><br><span class="line"></span><br><span class="line">app.get(&#x27;/user/getlist&#x27;, function (req, res) &#123;</span><br><span class="line">    res.setHeader(&#x27;Content-type&#x27;, &#x27;application/json&#x27;);</span><br><span class="line">    res.send(&#123;</span><br><span class="line">        status: 200,</span><br><span class="line">        data: dataList</span><br><span class="line">    &#125;);</span><br><span class="line">&#125;)</span><br><span class="line"></span><br><span class="line">app.listen(8000, function (err) &#123;</span><br><span class="line">    console.log(&#x27;listening port 8000...&#x27;);</span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure>
<p>jwt.js 文件, 我们在这个文件里引入了JWT的包<code>jsonwebtoken</code>. 它自带一些方法，比如签名<code>jwt.sign()</code>, 校验<code>jwt.verify()</code>. 这里面的<code>privateKey</code>就是上文中我们说到的用于签名的密钥，这里用一个简单的字符串代替了。</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br></pre></td><td class="code"><pre><span class="line">**jwt.js**</span><br><span class="line">const jwt = require(&#x27;jsonwebtoken&#x27;);</span><br><span class="line"></span><br><span class="line">class JwtUtil &#123;</span><br><span class="line">    constructor(data) &#123;</span><br><span class="line">        this.data = data;</span><br><span class="line">        this.privateKey = &#x27;helloworld&#x27;;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    generateToken() &#123;</span><br><span class="line">        const data = this.data;</span><br><span class="line">        const created = Math.floor(Date.now() / 1000);</span><br><span class="line">        const token = jwt.sign(&#123;</span><br><span class="line">            data,</span><br><span class="line">            exp: created + 60 * 3 // 3 minutes will be expire</span><br><span class="line">        &#125;, this.privateKey);</span><br><span class="line">        return token;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    verifyToken() &#123;</span><br><span class="line">        const token = this.data;</span><br><span class="line">        try&#123;</span><br><span class="line">            const result = jwt.verify(token, this.privateKey);</span><br><span class="line">            const currentTime = Math.floor(Date.now() / 1000);</span><br><span class="line">            if (result &amp;&amp; currentTime &lt;= result.exp) &#123;</span><br><span class="line">                return &#123; status: true &#125;;</span><br><span class="line">            &#125;</span><br><span class="line">            return &#123; status: false, msg: &#x27;token error&#x27;&#125;;</span><br><span class="line">        &#125;catch(e) &#123;</span><br><span class="line">            return &#123; status: false, msg: e.message &#125;;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">module.exports = JwtUtil;</span><br></pre></td></tr></table></figure>
<h3 id="案例运行步骤及效果"><a href="#案例运行步骤及效果" class="headerlink" title="案例运行步骤及效果"></a>案例运行步骤及效果</h3><p>案例是非常简单的一个基于express的node.js案例，很多jwt的方法没有详细介绍，这里只是让大家了解下它的用法， 同时让不怎么接触后端的前端小伙伴更好地理解身份验证的流程。</p>
<ol>
<li>首先用node命令将server.js文件启动起来<code>node server.js</code>，监听8000端口。</li>
<li>这时候我们就可以在浏览器里访问<code>localhost:8000/index.html</code>站点了。<br> 大概长这样。页面只放置了一个查看列表的按钮</li>
</ol>
<p><img src="/didiblog/images/jwt-demonstration/jwt-demo-picture2.png" alt="image.png"><br>3. 点击<code>查看列表</code>按钮，发送请求查看产品列表，这时候验证请求头没有token，显示登录窗口</p>
<p><img src="/didiblog/images/jwt-demonstration/jwt-demo-picture3.png" alt="image.png"><br>4. 输入我们模拟的用户名和账号</p>
<p><img src="/didiblog/images/jwt-demonstration/jwt-demo-picture4.png" alt="image.png"><br>5. 验证通过，返回JWT给到客户端，客户端重新发起请求获取产品列表<br>    <img src="/didiblog/images/jwt-demonstration/jwt-demo-picture5.png" alt="image.png"><br>6. 然后我们到localstorage里面看看token长什么样，就是用点<code>(.)</code>隔开的三段字符串</p>
<p><img src="/didiblog/images/jwt-demonstration/jwt-demo-picture6.png" alt="image.png"><br>7. 我们可以尝试再次刷新页面，然后去点击<code>查看列表</code>按钮，发现这时候就不再需要登录了。</p>
<h2 id="JWT的特点"><a href="#JWT的特点" class="headerlink" title="JWT的特点"></a>JWT的特点</h2><ol>
<li>JWT默认不加密，生成token后，可以用密钥再加密一次。所以没加密的时候不要把敏感信息写入</li>
<li>JWT不仅可以用于认证还可以用于信息交换，降低服务器查询数据库次数</li>
<li>JWT的缺点是，一旦JWT签发了，在到期之前一直有效，除非有额外的逻辑</li>
<li>JWT本身包含了认证信息，一旦泄露，任何人都还可以获得该令牌的所有权限，所以有效期应该设置短些，如果是重要的权限还是需要二次认证的。</li>
<li>为了减少盗用，JWT 不应该使用 HTTP 协议明码传输，要使用 HTTPS 协议传输。</li>
</ol>
<h2 id="结束语"><a href="#结束语" class="headerlink" title="结束语"></a>结束语</h2><p>JWT是现在比较流行的跨域身份验证解决方案，本文简单地介绍了它的原理，特点，数据组成等。同时用一个简单的小案例带大家了解它的实际用法，希望可以帮助到想要了解它的小伙伴。码字不易，喜欢的小伙伴点赞收藏吧</p>

      
    </div>
    <div class="article-footer">
      <blockquote class="mt-2x">
  <ul class="post-copyright list-unstyled">
    
    <li class="post-copyright-link hidden-xs">
      <strong>本文链接：</strong>
      <a href="https://guoyayunhappy.gitee.io/didiblog/2023/12/16/jwt-demonstration/" title="一文带你了解JWT以及在Nodejs中的应用" target="_blank" rel="external">https://guoyayunhappy.gitee.io/didiblog/2023/12/16/jwt-demonstration/</a>
    </li>
    
    <li class="post-copyright-license">
      <strong>版权声明： </strong> 本博客所有文章除特别声明外，均采用 <a href="http://creativecommons.org/licenses/by/4.0/deed.zh" target="_blank" rel="external">CC BY 4.0 CN协议</a> 许可协议。转载请注明出处！
    </li>
  </ul>
</blockquote>


<div class="panel panel-default panel-badger">
  <div class="panel-body">
    <figure class="media">
      <div class="media-left">
        <a href="https://gitee.com/GuoyayunHappy" target="_blank" class="img-burn thumb-sm visible-lg">
          <img src="/didiblog/images/avatar.jpg" class="img-rounded w-full" alt="">
        </a>
      </div>
      <div class="media-body">
        <h3 class="media-heading"><a href="https://gitee.com/GuoyayunHappy" target="_blank"><span class="text-dark">一枚@大帅锅</span><small class="ml-1x">CV工程师</small></a></h3>
        <div>个人简介。</div>
      </div>
    </figure>
  </div>
</div>


    </div>
  </article>
  
    
  <section id="comments">
  	
      <div id="vcomments"></div>
    
  </section>


  
</div>

  <nav class="bar bar-footer clearfix" data-stick-bottom>
  <div class="bar-inner">
  
  <ul class="pager pull-left">
    
    <li class="prev">
      <a href="/didiblog/2024/02/21/better-to-know-signature-and-certificate/" title="一文读懂加密，摘要，数字签名和证书"><i class="icon icon-angle-left" aria-hidden="true"></i><span>&nbsp;&nbsp;上一篇</span></a>
    </li>
    
    
    <li class="next">
      <a href="/didiblog/2023/10/02/regexp-dynamic-pattern/" title="模板正则表达式--动态替换字符"><span>下一篇&nbsp;&nbsp;</span><i class="icon icon-angle-right" aria-hidden="true"></i></a>
    </li>
    
    
  </ul>
  
  
  <!-- Button trigger modal -->
  <button type="button" class="btn btn-fancy btn-donate pop-onhover bg-gradient-warning" data-toggle="modal" data-target="#donateModal"><span>赏</span></button>
  <!-- <div class="wave-icon wave-icon-danger btn-donate" data-toggle="modal" data-target="#donateModal">
    <div class="wave-circle"><span class="icon"><i class="icon icon-bill"></i></span></div>
  </div> -->
  
  
  <div class="bar-right">
    
    <div class="share-component" data-sites="weibo,qq,wechat,facebook,twitter" data-mobile-sites="weibo,qq,qzone"></div>
    
  </div>
  </div>
</nav>
  
<!-- Modal -->
<div class="modal modal-center modal-small modal-xs-full fade" id="donateModal" tabindex="-1" role="dialog">
  <div class="modal-dialog" role="document">
    <div class="modal-content donate">
      <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
      <div class="modal-body">
        <div class="donate-box">
          <div class="donate-head">
            <p>感谢您的支持，我会继续努力的!</p>
          </div>
          <div class="tab-content">
            <div role="tabpanel" class="tab-pane fade active in" id="alipay">
              <div class="donate-payimg">
                <img src="/didiblog/images/donate/alipayimg.png" alt="扫码支持" title="扫一扫" />
              </div>
              <p class="text-muted mv">扫码打赏，你说多少就多少</p>
              <p class="text-grey">打开支付宝扫一扫，即可进行扫码打赏哦</p>
            </div>
            <div role="tabpanel" class="tab-pane fade" id="wechatpay">
              <div class="donate-payimg">
                <img src="/didiblog/images/donate/wechatpayimg.png" alt="扫码支持" title="扫一扫" />
              </div>
              <p class="text-muted mv">扫码打赏，你说多少就多少</p>
              <p class="text-grey">打开微信扫一扫，即可进行扫码打赏哦</p>
            </div>
          </div>
          <div class="donate-footer">
            <ul class="nav nav-tabs nav-justified" role="tablist">
              <li role="presentation" class="active">
                <a href="#alipay" id="alipay-tab" role="tab" data-toggle="tab" aria-controls="alipay" aria-expanded="true"><i class="icon icon-alipay"></i> 支付宝</a>
              </li>
              <li role="presentation" class="">
                <a href="#wechatpay" role="tab" id="wechatpay-tab" data-toggle="tab" aria-controls="wechatpay" aria-expanded="false"><i class="icon icon-wepay"></i> 微信支付</a>
              </li>
            </ul>
          </div>
        </div>
      </div>
    </div>
  </div>
</div>



</main>

  <footer class="footer" itemscope itemtype="http://schema.org/WPFooter">
	
	
    <ul class="social-links">
    	
        <li><a href="https://gitee.com/GuoyayunHappy" target="_blank" title="Github" data-toggle=tooltip data-placement=top><i class="icon icon-github"></i></a></li>
        
        <li><a href="/didiblog/atom.xml" target="_blank" title="Rss" data-toggle=tooltip data-placement=top><i class="icon icon-rss"></i></a></li>
        
    </ul>

    <div class="copyright">
    	
        <div class="publishby">
        	Theme by <a href="https://github.com/cofess" target="_blank"> cofess </a>base on <a href="https://github.com/cofess/hexo-theme-pure" target="_blank">pure</a>.
        </div>
    </div>
</footer>
  <script src="//cdn.jsdelivr.net/npm/jquery@1.12.4/dist/jquery.min.js"></script>
<script>
window.jQuery || document.write('<script src="js/jquery.min.js"><\/script>')
</script>

<script src="/didiblog/js/plugin.min.js"></script>


<script src="/didiblog/js/application.js"></script>


    <script>
(function (window) {
    var INSIGHT_CONFIG = {
        TRANSLATION: {
            POSTS: '文章',
            PAGES: '页面',
            CATEGORIES: '分类',
            TAGS: '标签',
            UNTITLED: '(未命名)',
        },
        ROOT_URL: '/didiblog/',
        CONTENT_URL: '/didiblog/content.json',
    };
    window.INSIGHT_CONFIG = INSIGHT_CONFIG;
})(window);
</script>

<script src="/didiblog/js/insight.js"></script>






   




   
    
  <script src="//cdn1.lncld.net/static/js/3.0.4/av-min.js"></script>
  <script src="//cdn.jsdelivr.net/npm/valine"></script>
  <script type="text/javascript">
  var GUEST = ['nick', 'mail', 'link'];
  var meta = 'nick,mail,link';
  meta = meta.split(',').filter(function(item) {
    return GUEST.indexOf(item) > -1;
  });
  new Valine({
    el: '#vcomments',
    verify: false,
    notify: false,
    appId: '',
    appKey: '',
    placeholder: 'Just go go',
    avatar: 'mm',
    meta: meta,
    pageSize: '10' || 10,
    visitor: false
  });
  </script>

     







</body>
</html>